<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="language" content="en" />
		<title>Map for BSTU</title>
		<script type="text/javascript" src="script/jquery-1.8.2.min.js"></script>
		<script src="script/OpenLayers.js"></script>
		<script src="script/jquery.json-2.3.min.js"></script>
		<script type="text/javascript">
			
			var objects;

			
			var curObject=null;
			var oldObject=null;
			var newObject=null;
			var curAction="L";		
			
			var map;
			var objectLayer;
			var tempLayer=null;
			var defaultStyle=OpenLayers.Feature.Vector.style['default'];
			var selectedStyle=	{
									strokeColor: "red", 
									fillColor: "red",
									fillOpacity: "0.3",
									strokeOpacity: "0.7", 
									strokeWidth: 2, 
									cursor: "pointer"
								};
			
			$(document).ready(function(){
				updateView();
					
				$("#add-building-button").click(function(){
					var myNewObj=new Object();
					myNewObj.id=-1;
					myNewObj.type="B";
					myNewObj.coords=[];
					
					oldObject=curObject;
					if(curObject!=null && curObject!=undefined){
						objectLayer.drawFeature(curObject,defaultStyle);
					}
					curObject=getMapObject(myNewObj);
					objectLayer.addFeatures([curObject]);
					
					curAction="A";
					updateView();
				});
				
				$("#add-street-button").click(function(){
					var myNewObj=new Object();
					myNewObj.id=-1;
					myNewObj.type="S";
					myNewObj.coords=[];
					
					oldObject=curObject;
					if(curObject!=null && curObject!=undefined){
						objectLayer.drawFeature(curObject,defaultStyle);
					}
					curObject=getMapObject(myNewObj);
					objectLayer.addFeatures([curObject]);
					
					curAction="A";
					updateView();
				});
				
				$("#edit-object-button").click(function(){
					curAction="E";
					updateView();
					
					//copy object
					oldObject=getMapObject(getMyObject(curObject));
				});
				
				$("#delete-object-button").click(function(){
					//deleting
					objectLayer.removeFeatures(curObject);
					curObject=objectLayer.features[0];
					
					if(curObject!=null && curObject!=undefined)
						objectLayer.drawFeature(curObject,selectedStyle);
					
					//ЗАПРОС НА УДАЛЕНИЕ ОБЪЕКТА**************************
					$.ajax({
						type:'POST',
						url: '/map/ajax/delete.php',           // указываем URL и
						dataType : 'text',                     // тип загружаемых данных
						data: 'curObjectId='+curObject.id+"&curObjectType="+curObject.type;
					});
					//****************************************************
					
					curAction="L";
					updateView();
				});
				
				$("#save-button").click(function(){
					if(tempLayer!=null)
					{
						tempLayer.removeAllFeatures();
					}
					oldObject=null;
					curAction="L";
					updateView();

					//ЗАПРОС НА СОХРАНЕНИЕ ИЗМЕНЕНИЙ**********************
					$.ajax({
						type:'POST',
						url: '/map/ajax/save.php',             // указываем URL и
						dataType : 'json',                     // тип загружаемых данных
						data: 'curObject='+$.toJSON(getMyObject(curObject)),
						success: function(data){
							curObject.id = data; 
						} 
					});
					//****************************************************
				});
							
				$("#cancel-button").click(function(){
					if(tempLayer!=null)
					{
						tempLayer.removeAllFeatures();
					}
					
					objectLayer.removeFeatures([curObject]);
					curObject=oldObject;
					oldObject=null;
					objectLayer.addFeatures(curObject);
					objectLayer.drawFeature(curObject,selectedStyle);
					curAction="L";
					updateView();
				});
				
				$("#erase-last-point-button").click(function(){
					if(tempLayer!=null)
					{
						tempLayer.removeAllFeatures();
					}
					if(curObject.myExt.type=="S")
					{
						curObject.geometry.components.pop();
					}
					else
					{
						if(curObject.geometry.components.length<=2)
							curObject.geometry.components=[];
						else if(curObject.geometry.components.length==3)
						{
							curObject.geometry.components[curObject.geometry.components.length-2]=curObject.geometry.components[curObject.geometry.components.length-1];
							curObject.geometry.components.pop();
						}
						else
							curObject.geometry.removeComponent(curObject.geometry.components[curObject.geometry.components.length-2]);
					}
					objectLayer.drawFeature(curObject,selectedStyle);
					updateView();
				});
			
				$("#street-name").change(function(){
					curObject.myExt.streetName=$("#street-name").val();
					updateView();
				});
				
				$("#traffic-direction").change(function(){
					curObject.myExt.direction=$("#traffic-direction").val();
					updateView();
				});

				$("#house-number").change(function(){
					curObject.myExt.house=$("#house-number").val();
					updateView();
				});
			});

				function getMap() {
					map = new OpenLayers.Map("OSMap",{ controls: [new OpenLayers.Control.Navigation({zoomWheelEnabled: false}), new OpenLayers.Control.MousePosition()] });//������������� �����
					var osmLayer = new OpenLayers.Layer.OSM();//�������� ���� �����
					map.addLayer(osmLayer);//���������� ����
					map.setCenter(new OpenLayers.LonLat(23.7433, 52.0955) //(�������, ������)
						  .transform(
							new OpenLayers.Projection("EPSG:4326"), // ��������������� � WGS 1984
							new OpenLayers.Projection("EPSG:900913") // ��������������� ��������
						  ), 18 // �������
						);
						
					//object layer
					objectLayer=new OpenLayers.Layer.Vector("Object Layer");
					//temp layer
					tempLayer=new OpenLayers.Layer.Vector("Temp Layer");
					
					map.addLayers([objectLayer,tempLayer]);
					
					loadAllObjects();
					addAllObjects();
					
					curObject=objectLayer.features[0];
					updateView();
					objectLayer.drawFeature(curObject,selectedStyle);
					
					map.events.register('click', map, function (e) {  
						var x=map.getLonLatFromViewPortPx(e.xy).lon;
						var y=map.getLonLatFromViewPortPx(e.xy).lat;
							
						if(curAction=="A" || curAction=="E")
						{
							var points=curObject.geometry.components;
							if(curObject.myExt.type=="S")
							{
								points.push(new OpenLayers.Geometry.Point(x,y));
							}
							else
							{
								if(points.length==0)
								{
									points.push(new OpenLayers.Geometry.Point(x,y));
									points.push(new OpenLayers.Geometry.Point(x,y));
								}
								else
								{
									var tmp=points[points.length-1];
									points[points.length-1]=new OpenLayers.Geometry.Point(x,y);
									points.push(tmp);
								}
							}
							objectLayer.drawFeature(curObject,selectedStyle);
							updateView();
						}
						else
						{
							objectLayer.drawFeature(curObject,defaultStyle);
							
							var point=new OpenLayers.Geometry.Point(x,y);
							
							//�������� ����� ������
							var features=objectLayer.features;
							curObject=features[0];
							var minDist=curObject.geometry.distanceTo(point,null);
							var curDist;
							for(var i=1;i<features.length;i++)
							{
								curDist=features[i].geometry.distanceTo(point,null)
								if(curDist<minDist)
								{
									minDist=curDist;
									curObject=features[i];
								}
							}
							
							//�������� ��������� ������
							updateView();
							//map.setCenter(new OpenLayers.LonLat(curObject.geometry.components[0].x,curObject.geometry.components[0].y));
							objectLayer.drawFeature(curObject,selectedStyle);
						}
					}); //���������� ������� ����� �� �����
					
					map.events.register('mousemove', map, function (e) {
						if(curAction=="A" || curAction=="E")
						{
							
							var x=map.getLonLatFromViewPortPx(e.xy).lon;
							var y=map.getLonLatFromViewPortPx(e.xy).lat;
							var mousePoint=new OpenLayers.Geometry.Point(x,y);
							tempLayer.removeAllFeatures();
							
							tempLayer.addFeatures([new OpenLayers.Feature.Vector(mousePoint)]);
							var point1=curObject.geometry.components[curObject.geometry.components.length-1];
							tempLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([mousePoint,point1]))]);
							
							if(curObject.myExt.type=="B")
							{
								point1=curObject.geometry.components[curObject.geometry.components.length-2];
								tempLayer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([mousePoint,point1]))]);
							}
						}
					});
				}
				
				function updateView()
				{
					var myObj=getMyObject(curObject);
					SetCurrentValues(myObj);
					ShowHideElements(myObj);
					EnableDisableElements(myObj);
				}
				
				function SetCurrentValues(myObj)
				{
					if(myObj!=null && myObj!=undefined)
					{
						if(myObj.type=="B")
							$("#object-type").html("Building");
						else
							$("#object-type").html("Street");
						$("#street-name").val(myObj.streetName);
						$("#house-number").val(myObj.house);
						$("#traffic-direction").val(myObj.direction);
					}
					else
					{
						$("#object-type").html("-");
						$("#street-name").val("O");
						$("#house-number").val("");
						$("#traffic-direction").val("B");
					}
				}
				
				function ShowHideElements(myObj)
				{
					if(curAction=="L")
					{			
						$("#erase-last-point-button").hide();
						$("#save-button").hide();
						$("#cancel-button").hide();
					}
					else if(curAction=="E" || curAction=="A")
					{
						$("#erase-last-point-button").show();
						$("#save-button").show();
						$("#cancel-button").show();
					}
					
					if(myObj==null || myObj==undefined)
					{
						$("#street-name-container").hide();
						$("#house-number-container").hide();
						$("#traffic-direction-container").hide();
					}
					else
					{
						$("#street-name-container").show();					
						if(myObj.type=="B")
						{
							$("#house-number-container").show();
							$("#traffic-direction-container").hide();
						}
						else if(myObj.type=="S")
						{
							$("#house-number-container").hide();
							$("#traffic-direction-container").show();
						}										
					}
				}

				function EnableDisableElements(myObj)
				{
					if(curAction=="L")
					{
						$("#add-building-button").prop("disabled",false);
						$("#add-street-button").prop("disabled",false);
						$("#edit-object-button").prop("disabled",(myObj==null || myObj==undefined));
						$("#delete-object-button").prop("disabled",false);
						
						$("#traffic-direction").prop("disabled","disabled");
						$("#house-number").prop("disabled","disabled");
						$("#street-name").prop("disabled","disabled");
					}
					else if(curAction=="E" || curAction=="A")
					{
						$("#add-building-button").prop("disabled",true);
						$("#add-street-button").prop("disabled",true);
						$("#edit-object-button").prop("disabled",true);
						$("#delete-object-button").prop("disabled",true);
						
						$("#traffic-direction").removeAttr("disabled");
						$("#house-number").removeAttr("disabled");
						$("#street-name").removeAttr("disabled");
						
						if((myObj.type=='S' && (myObj.coords.length<2 || myObj.direction=="O" || myObj.direction==null || myObj.direction==undefined)) || (myObj.type=='B' && (myObj.coords.length<3 || myObj.house=="" || myObj.house==null || myObj.house==undefined)) || myObj.streetName==null || myObj.streetName==undefined || myObj.streetName=="0")
						{
							$("#save-button").prop("disabled",true);
						}
						else
						{
							$("#save-button").prop("disabled",false);
						}
						
						if(myObj.coords.length==0)
						{
							$("#erase-last-point-button").prop("disabled",true);
						}
						else
						{
							$("#erase-last-point-button").prop("disabled",false);
						}
					}
				}
				
				function getMapObject(myObject)
				{
					var myExt=new Object();
					myExt.id=myObject.id;
					myExt.type=myObject.type;
					myExt.streetName=myObject.streetName;
					myExt.direction=myObject.direction;
					myExt.house=myObject.house;
					
					var points=[];
					var point;
					for(var i=0;i<myObject.coords.length;i++)
					{
						point=new OpenLayers.Geometry.Point(myObject.coords[i].lon,myObject.coords[i].lat);
						points.push(point);
					}
					
					var tmp;
					if(myObject.type=="S")
					{
						tmp=new OpenLayers.Geometry.LineString(points);
					}
					else
					{
						tmp=new OpenLayers.Geometry.LinearRing(points);
					}
					var feature = new OpenLayers.Feature.Vector(tmp,null, null);
					feature.myExt=myExt;
					return feature;
				}
				
				function getMyObject(mapObject)
				{
					if(mapObject==null || mapObject==undefined)
						return null;
				
					var myObject=new Object();
					
					myObject.id=mapObject.myExt.id;
					myObject.type=mapObject.myExt.type;
					myObject.streetName=mapObject.myExt.streetName;
					myObject.direction=mapObject.myExt.direction;
					myObject.house=mapObject.myExt.house;
					
					var points=mapObject.geometry.components;
					var coords=[];
					var coord;
					for(var i=0;i<points.length;i++)
					{
						coord=new Object();
						coord.lon=points[i].x;
						coord.lat=points[i].y;
						coords.push(coord);
					}
					if(myObject.type=="B")
					{
						coords.pop();
					}
					
					myObject.coords=coords;
					
					return myObject;
				}
				
				function loadAllObjects()
				{
					$.ajax({
						url: 'ajax/getObjects.php',
						async: false,
						success: 
						function(data){
							objects = JSON.parse( data ); 
						} 
					});
				}
				
				function addAllObjects()
				{
					var features=[];
					for(var i=0;i<objects.length;i++)
					{
						features.push(getMapObject(objects[i]));
					}
					objectLayer.addFeatures(features);
				}
		</script>
		
		<style type="text/css">
			#OSMap
			{
				position:relative;
				float:left;
				width:500px;
				height:300px;
				margin-right:30px;
			}
			
			.field-label
			{
				display: inline-block;
				width:120px;
			}
		</style>
	</head>
	 <body onload="getMap();">
		<div>
			<h2>OpenStreetMap</h2>
			<div id="OSMap">
			</div>
		
			<div id="select-action-panel">
				<input type="button" id="add-street-button" value="Add street"/>
				<input type="button" id="add-building-button" value="Add building"/>
				<input type="button" id="edit-object-button" value="Edit object"/>
				<input type="button" id="delete-object-button" value="Delete object" />
			</div>
			<div id="object-info-panel">
				<div id="object-type-container">
					<span class="field-label">Object type: </span>
					<span id="object-type"></span>
				</div>
				<div id="street-name-container">
					<span class="field-label">Street name</span>
					<select id="street-name">
						<!--load from server (id,text)-->
						<option value="0">...</option>
						<option value="1">Moscow street</option>
						<option value="2">Sovietskaja street</option>
						<option value="3">Lenina street</option>
					</select>
				</div>
				<div id="house-number-container">
					<span class="field-label">House number:</span>
					<input type="text" id="house-number" />
				</div>
				<div id="traffic-direction-container">
					<span class="field-label">Traffic direction:</span>
					<select id="traffic-direction">
						<option value="O">...</option>
						<option value="B">Bidirected</option>
						<option value="F">First to last</option>
						<option value="L">Last ot first</option>
					</select>
				</div>
				<div>
					<input type="button" id="erase-last-point-button" value="Erase last point of object" />
				</div>
				<div>
					<input type="button" id="save-button" value="Save object"/>
					<input type="button" id="cancel-button" value="Cancel action" />
				</div>
			</div>
		</div>
	 </body>
</html>